package com.hotlcc.bark.service.impl;

import cn.hutool.core.lang.Assert;
import com.hotlcc.bark.dao.DevicesJpaRepository;
import com.hotlcc.bark.dao.entity.Devices;
import com.hotlcc.bark.service.DevicesService;
import com.hotlcc.bark.service.converter.DevicesConverter;
import com.hotlcc.bark.service.dto.DevicesDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@CacheConfig(cacheNames = "db:devices")
public class DevicesServiceImpl implements DevicesService {
    @Autowired
    private DevicesJpaRepository devicesJpaRepository;

    @Override
    @CachePut(key = "'keyMap:' + #deviceKey")
    public DevicesDTO save(String deviceKey, String deviceToken) {
        Assert.notBlank(deviceKey, "device key is empty");
        Assert.notBlank(deviceToken, "device token is empty");

        Devices entity = devicesJpaRepository.getOneByKey(deviceKey);
        if (entity == null) {
            entity = new Devices();
            entity.setKey(deviceKey);
            entity.setToken(deviceToken);
        } else {
            entity.setToken(deviceToken);
        }

        devicesJpaRepository.save(entity);

        return DevicesConverter.INSTANCE.convertToDevicesDTO(entity);
    }

    @Override
    @Cacheable(key = "'keyMap:' + #deviceKey")
    public DevicesDTO queryOne(String deviceKey) {
        Assert.notBlank(deviceKey, "device key is empty");

        Devices entity = devicesJpaRepository.getOneByKey(deviceKey);
        return DevicesConverter.INSTANCE.convertToDevicesDTO(entity);
    }
}
